/**
 * 生产随机字符串
 * @param {String} len 生成的字符串长度
 * @returns {String}
 */
const randomString = (len = 10) => {
	const $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	const maxPos = $chars.length;
	let pwd = '';
	for (let i = 0; i < len; i++) {
		pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
};


/**
 * 判断是否为空值  注意 0 为非空值
 * @param {*} value
 * @returns Boolean
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const emptyValue = (value: any) => {
	if (value !== 0 && !value) {
		return true;
	}
	return Object.prototype.toString.call(value) === '[object Array]' && !value.length;
};
type Func = (item: any) => string;
interface Props {
	findKey?: string;
	filterVal: any;
	returnKey?: string | Func;
	childrenKey?: string;
	returnParentName?: boolean;
}
/**
 * @description 通过id获取树节点名称
 * @param {Array} tree 树
 * findKey = 'id',过滤键名
   filterVal,//过滤值
   returnKey = 'name',节点名称字段
   childrenKey = 'children',子节点集合字段
   returnParentName = false,是否返回父节点名称
 * @return {String} 名称
 */
export const getNodeName = (
	tree: Array<any>,
	{
		findKey = 'id',
		filterVal,
		returnKey = 'name',
		childrenKey = 'children',
		returnParentName = false,
	}: Props
): string => {
	if (!tree || !tree.length) return '';

	for (const item of tree) {
		if (item[findKey] === filterVal) {
			if (typeof returnKey === 'function') return returnKey(item);
			return item[returnKey];
		}
		const childResult: string = getNodeName(item[childrenKey], {
			findKey,
			filterVal,
			returnKey,
			childrenKey,
			returnParentName,
		});
		if (childResult) {
			let parentName = '';
			if (typeof returnKey === 'function') {
				parentName = returnKey(item);
			} else {
				parentName = item[returnKey];
			}
			return returnParentName ? `${parentName}/${childResult}` : childResult;
		}
	}
	return '';
};

export { randomString, emptyValue };
